import plugin from '../../../lib/plugins/plugin.js'
import fs from 'fs'
import lodash from 'lodash'
import { Config, Data } from '../components/index.js'
import { puppeteer } from '../model/index.js'

export class tx_help extends plugin {
  constructor () {
    super({
      name: '小月帮助',
      event: 'message',
      priority: -999,
      rule: [
        {
          reg: '^#?小月(群管(帮助)?|帮助)$',
          fnc: 'messages'
        },
        {
          reg: '^#?(附加)?(命令|帮助|菜单|help|说明|功能|指令|使用说明)$',
          fnc: 'addmes'
        }
      ]
    })
  }

  async messages () {
    return await help(this.e)
  }

  async addmes () {
    let config = await Config.xyss
    if (!config.defaulthelp) {
      if (!/附加/.test(this.e.msg)) { return false }
    }
    return await help(this.e)
  }
}

async function help (e) {
  let custom = {}
  let index = e.msg.includes('群管') ? 'qghelp' : e.msg.includes('小月') ? 'help' : 'addhelp'
  let { diyCfg, sysCfg } = await Data.importCfg(index)

  let helpConfig = lodash.defaults(diyCfg.helpCfg || {}, custom.helpCfg, sysCfg.helpCfg)
  let helpList = diyCfg.helpList || custom.helpList || sysCfg.helpList
  let helpGroup = []

  lodash.forEach(helpList, (group) => {
    if (group.auth && group.auth === 'master' && !e.isMaster) {
      return true
    }

    lodash.forEach(group.list, (help) => {
      let icon = help.icon * 1
      if (!icon) {
        help.css = 'display:none'
      } else {
        let x = (icon - 1) % 10
        let y = (icon - x - 1) / 10
        help.css = `background-position:-${x * 50}px -${y * 50}px`
      }
    })

    helpGroup.push(group)
  })
  let bg = await rodom()
  let colCount = 3
  return await puppeteer.render('help/index', {
    helpCfg: helpConfig,
    helpGroup,
    bg,
    colCount,
    element: 'default'
  }, {
    e,
    scale: 2.0
  })
}

const rodom = async function () {
  let image = fs.readdirSync('./plugins/xiaoyue-plugin/resources/help/imgs/')
  let list_img = []
  for (let val of image) {
    list_img.push(val)
  }
  let imgs = list_img.length == 1 ? list_img[0] : list_img[lodash.random(0, list_img.length - 1)]
  return imgs
}
